//
//  PAgeContentView.swift
//  DouYuZB
//
//  Created by DSDL on 2016/10/26.
//  Copyright © 2016年 鼎商动力. All rights reserved.
//

import UIKit
protocol PageContentViewDelegate: class {
    func pageContentView(_ content: PAgeContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}

private let contentCellID = "contentCellID"
class PAgeContentView: UIView {
    
    //MARK: - 定义属性
    fileprivate var childVcsArr: [UIViewController] //子控制器数组
    fileprivate weak var parentViewController: UIViewController? //父控制器
    fileprivate var startOffsetX: CGFloat = 0
    weak var delegate:PageContentViewDelegate?
    fileprivate var isForbidScrollDelegate: Bool = false

    //MARK: - 懒加载属性
    fileprivate lazy var collectionView: UICollectionView = { [weak self] in
        //1.创建布局
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        //2.创建collectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.isPagingEnabled = true
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID)
        return collectionView
    }()
    //便利构造器
    init(frame: CGRect, childVcsArr: [UIViewController], parentViewController: UIViewController?) {
        self.childVcsArr = childVcsArr
        self.parentViewController = parentViewController
        super.init(frame: frame)
        
        //设置UI
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}
//MARK: - 设置UI界面
extension PAgeContentView {
    
    fileprivate func setupUI(){
        
        //1.将子控制器添加到父控制器中
        for childVc in childVcsArr {
            parentViewController?.addChildViewController(childVc)
        }
        //2.添加collectionView
        addSubview(collectionView)
        collectionView.frame = bounds
    }
}

//MARK: - UICollectionViewDataSource
extension PAgeContentView:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcsArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //1.创建cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath)
        
        //2.给cell设置内容
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVc = childVcsArr[(indexPath as NSIndexPath).item]
        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)
        return cell
    }
}

//MARK: - UICollectionViewDelegate
extension PAgeContentView: UICollectionViewDelegate {
    //当用户首次在某个方向上进行拖动时得到通知。这个方法会得到被作为参数传递的滚动视图指针，也同样可以从中读取 contentOffset 属性
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isForbidScrollDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    //会在视图滚动时收到通知。包括一个指向被滚动视图的指针，从中可以读取contentOffset属性以确定其滚动到的位置。
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //0.判断是否是点击事件
        if  isForbidScrollDelegate { return }
        
        // 1.定义要获取的内容
        var sourceIndex = 0 //源
        var targetIndex = 0 //目标
        var progress : CGFloat = 0
        // 2.判断左滑还是右滑
        let currentOffsetX = scrollView.contentOffset.x
        let ratio = currentOffsetX / scrollView.bounds.width
     
        if currentOffsetX > startOffsetX{ //左滑
            //1.计算progress
            progress = ratio - floor(ratio)
            //2.计算 scurceIndex
            sourceIndex = Int(ratio)
            //3.计算targetIndex
            targetIndex  = sourceIndex + 1
            if targetIndex >= childVcsArr.count {
                targetIndex = childVcsArr.count - 1
            }
            //4.如果完全划过去
            if currentOffsetX - startOffsetX == scrollView.bounds.width {
                progress = 1
                targetIndex = sourceIndex
            }
            
        }else{//右滑
            //1.计算progress
            progress = 1 - (ratio - floor(ratio))
            //2.计算 targetIndex
            targetIndex = Int(ratio)
            //3.计算scurceIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childVcsArr.count {
                sourceIndex = childVcsArr.count - 1
            }
        }
        //代理传值
        delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
    }
}

//MARK: - 对外暴露的方法
extension PAgeContentView {
    func setCurrentIndex(_ currentIndex: Int) {
        //1.记录需要禁止执行的代理方法
        isForbidScrollDelegate = true
        
        //2.滚动到正确位置
        let offsetX = CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
    }
}
